﻿using System.Collections.Generic;
using System.Linq;
using IapService.Entity;
using NHibernate.Criterion;
using NHibernate.Linq;

namespace IapService.Data
{
    public class VectorData : Data<Vector>
    {
        public new Vector Save(Vector item)
        {
            using (var session = Session)
            {
                session.SaveOrUpdate(item);

                foreach (var vectorImage in item.VectorImages)
                {
                    session.SaveOrUpdate(vectorImage);
                }
                foreach (var vectorTag in item.VectorTags)
                {
                    session.SaveOrUpdate(vectorTag);
                }
                session.Flush();
            }
            return item;
        }

        public List<Vector> GetByTag(int[] tagIds)
        {
            List<Vector> items;
            using (var session = Session)
            {
                //session.Query<VectorTag>().Where();k
                var vectorIdByTags = session.CreateCriteria<VectorTag>()
                    .Add(Restrictions.In("Tag.Id", tagIds))
                    .List<VectorTag>();
                var vectorIds2 = vectorIdByTags.Select(s => s.VectorId).ToArray();

                items = session.CreateCriteria<Vector>()
                    .Add(Restrictions.In("Id", vectorIds2))
                    .List<Vector>()
                    .ToList();

                var vectorsRemove = new List<Vector>();
                foreach (var tagId in tagIds)
                {
                    vectorsRemove.AddRange(items.Where(item => item.VectorTags.Count(s => s.Tag.Id == tagId) == 0));
                }
                foreach (var vectorRemove in vectorsRemove)
                {
                    items.Remove(vectorRemove);
                }

            }
            return items;
        }

        public bool ValidRemove(int id)
        {
            bool canRemove;
            List<Vector> items;
            using (var session = Session)
            {
                var samples = session.CreateCriteria<Sample>()
                    .Add(Restrictions.Eq("Vector.Id", id))
                    .List<Sample>();
                canRemove = !samples.Any();
            }
            return canRemove;
        }

        public new Vector Remove(Vector item)
        {
            List<Sample> samples;
            using (var session = Session)
            {
                session.Delete(item);
                session.Flush();
                samples = (List<Sample>)session.CreateCriteria<Sample>()
                                     .Add(Restrictions.Eq("Vector.Id", item.Id))
                                     .List<Sample>();
            }
            foreach (var sample in samples)
            {
                var result = new SampleData().Remove(sample);
            }
            return item;
        }
    }
}